/**
* All Rights Reserved , Copyright (C) 2022 , 青岛鼎信通讯股份有限公司
*
* AppUserUseInfoService
* 用户使用信息
*
* 修改纪录
* 2022-12-23 版本：1.0 wuyuyang 创建。
* @version 版本：1.0
* @author 作者：wuyuyang
* 创建日期：2022-12-23
*/
package com.topscomm.appv2.service.impl;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.topscomm.appv2.AppTreeModel;
import com.topscomm.appv2.SystemConst;
import com.topscomm.appv2.pojo.AppAreaInitializationConfigEntity;
import com.topscomm.appv2.pojo.AppUserUseInfoEntity;
import com.topscomm.basic.exception.MessageException;
import com.topscomm.basic.exception.ServiceException;
import com.topscomm.basic.util.PrimaryKeyUtil;
import com.topscomm.cbo.pojo.*;
import com.topscomm.cbo.service.ICboDeptService;
import com.topscomm.cbo.service.ICboModuleService;
import com.topscomm.cbo.service.ICboPermissionModuleService;
import com.topscomm.cbo.service.impl.CboItemDetailsService;
import com.topscomm.cbo.service.impl.CboRoleService;
import com.topscomm.cbo.service.impl.CboUserRoleService;
import com.topscomm.cbo.service.impl.CboUserService;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.pub.util.StringUtil;
import com.topscomm.tap.common.DatacodeCache;
import com.topscomm.tap.common.ParameterCache;
import com.topscomm.tap.common.SessionUserBean;
import com.topscomm.tap.threadlocal.ThreadLocalContext;
import org.apache.commons.lang3.StringUtils;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.topscomm.appv2.service.IAppUserUseInfoService;
import com.topscomm.appv2.service.impl.auto.AppUserUseInfoServiceAuto;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service(value = "appUserUseInfoService")
@Scope(value = "singleton")
public class AppUserUseInfoService extends AppUserUseInfoServiceAuto implements IAppUserUseInfoService {
    @Autowired
    private CboRoleService cboRoleService;
    @Autowired
    private CboUserRoleService cboUserRoleService;
    @Autowired
    private CboUserService cboUserService;
    @Autowired
    public CboItemDetailsService cboItemDetailsService;
    @Resource(name = "ehrSqlSessionTemplate")
    private SqlSessionTemplate ehrSqlSessionTemplate;
    @Resource(name = "mpmSqlSessionTemplate")
    private SqlSessionTemplate mpmSqlSessionTemplate;
    @Resource(name = "mmsSqlSessionTemplate")
    private SqlSessionTemplate mmsSqlSessionTemplate;
    @Resource(name = "meetSqlSessionTemplate")
    private SqlSessionTemplate meetSqlSessionTemplate;
    @Resource(name = "pmSqlSessionTemplate")
    private SqlSessionTemplate pmSqlSessionTemplate;
    @Resource(name = "cdmcSqlSessionTemplate")
    private SqlSessionTemplate cdmcSqlSessionTemplate;
    @Resource(name = "iscSqlSessionTemplate")
    private SqlSessionTemplate iscSqlSessionTemplate;
    @Resource(name = "oaSqlSessionTemplate")
    private SqlSessionTemplate oaSqlSessionTemplate;
    @Resource(name = "biSqlSessionTemplate")
    private SqlSessionTemplate biSqlSessionTemplate;
    @Resource(name = "scmSqlSessionTemplate")
    private SqlSessionTemplate scmSqlSessionTemplate;
    @Resource(name = "winSqlSessionTemplate")
    private SqlSessionTemplate winSqlSessionTemplate;
    @Resource(name = "erSqlSessionTemplate")
    private SqlSessionTemplate erSqlSessionTemplate;
    @Resource(name = "crmSqlSessionTemplate")
    private SqlSessionTemplate crmSqlSessionTemplate;
    @Resource(name = "hrSqlSessionTemplate")
    private SqlSessionTemplate hrSqlSessionTemplate;
    @Resource(name = "mspSqlSessionTemplate")
    private SqlSessionTemplate mspSqlSessionTemplate;
    @Resource(name = "omsSqlSessionTemplate")
    private SqlSessionTemplate omsSqlSessionTemplate;
    @Resource(name = "scrmfSqlSessionTemplate")
    private SqlSessionTemplate scrmfSqlSessionTemplate;
    @Autowired
    private ICboDeptService cboDeptService;
    @Autowired
    private ICboPermissionModuleService cboPermissionModuleService;
    @Autowired
    private ICboModuleService cboModuleService;
    @Autowired
    private AppAreaInitializationConfigService appAreaInitializationConfigService;
    @Autowired
    private  AppModuleIconService appModuleIconService;
    @Resource(name = "mybatisRedisTemplate")
    private RedisTemplate<String, Object> redisTemplate;
    // 缓存过期时间(秒)
    private static final int cacheLiveTime = 300;

    /***
     * @description: 查询所有用户一级目录权限
     * @param paraMap
     * @return
     * @author: hudeyong
     * @date:
     * @modify:
     */
    @Override
    public List<Map<String, Object>> queryOpenedModule(Map<String, Object> paraMap) {
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle("code like '80%' and code != '80' and opened = '1'");
        List<Map<String, Object>> cboModuleList = cboModuleService.queryMapByWhere(sql.toString());
        List<Map<String, Object>> resultList = new ArrayList<>();
        for(Map<String, Object> moduleInfo : cboModuleList) {
            long parentid = ConvertUtil.convertToLong(moduleInfo.get("parentid"));
            String type = ConvertUtil.convertToString(moduleInfo.get("extendfield2"));
            if("1".equals(type) && queryExistRoot(parentid,cboModuleList)) {
                resultList.add(moduleInfo);
            }

        }
        // 组件上方搜索框
        if(paraMap.containsKey("qry_code") && !ConvertUtil.convertToString(paraMap.get("qry_code")).isEmpty()){
            String filtervalue = ConvertUtil.convertToString(paraMap.get("qry_code"));
            resultList = resultList.stream().
                    filter( e -> (filtervalue.equals(ConvertUtil.convertToString(e.get("code"))))).collect(Collectors.toList());
        }
        if(paraMap.containsKey("qry_name") && !ConvertUtil.convertToString(paraMap.get("qry_name")).isEmpty()){
            String filtervalue = ConvertUtil.convertToString(paraMap.get("qry_name"));
            resultList = resultList.stream().
                    filter( e -> (filtervalue.equals(ConvertUtil.convertToString(e.get("name"))))).collect(Collectors.toList());
        }
        return resultList;
    }

    public boolean queryExistRoot(long parentid, List<Map<String, Object>> queryList) {
        for (Map<String, Object> queryModuleInfo : queryList) {
            long id = ConvertUtil.convertToLong(queryModuleInfo.get("id"));
            if (parentid == id) {
                String code = ConvertUtil.convertToString(queryModuleInfo.get("code"));
                if (code.length() == 4) {
                    return true;
                } else {
                    parentid = ConvertUtil.convertToLong(queryModuleInfo.get("parentid"));
                    if (queryExistRoot(parentid, queryList)) {
                        return true;
                    }
                }
            }
        }
        return false;
    }



    /***
     * @description: 查询所有用户一级目录权限
     * @param paraMap
     * @return
     * @author: hudeyong
     * @date:
     * @modify:
     */
    public Map<String, Object> queryUserPermissionRealm(List<AppUserUseInfoEntity> appUserUseInfoList) {
        Map<String, Object> resultMap = new HashMap<>();
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle("SELECT id,code,name,opened FROM CBOMODULE WHERE CODE LIKE '80%' AND PARENTID = (SELECT Id FROM CBOMODULE WHERE CODE = '80') AND EXTENDFIELD2 = '0'");
        List<Map<String, Object>> moduleList = this.selectExecute(sql.toString());
        Map<String, Object> tempMap = new HashMap<>();
        for(Map<String, Object> module : moduleList){
            String moduleCode = ConvertUtil.convertToString(module.get("code"));
            tempMap = new HashMap<>();
            if("1".equals(ConvertUtil.convertToString(module.get("opened")))){
                // 公开模块，所有人都有
                tempMap.put("open","");
            } else{
                // 非公开模块，查找有权限的人
                sql.clear();
                sql.appendSingle("MODULEID  = '{0}'",ConvertUtil.convertToString(module.get("id")));
                List<CboPermissionModuleEntity> permissionModuleEntities = cboPermissionModuleService.queryByWhere(sql.toString());
                tempMap = queryUserByModule(permissionModuleEntities);
            }
            for(AppUserUseInfoEntity userUseInfoEntity : appUserUseInfoList){
                String usercode = userUseInfoEntity.getUsercode();
                String tempModule = resultMap.containsKey(usercode) ? (ConvertUtil.convertToString(resultMap.get(usercode)) + "," + moduleCode) : moduleCode;
                if(tempMap.containsKey("open")){
                    resultMap.put(usercode,tempModule);
                } else if(tempMap.containsKey(usercode)){
                    resultMap.put(usercode,tempModule);
                }
            }
        }
        return resultMap;
    }

    /***
     * @description: 查询模块可被哪些用户可见
     * @param paraMap
     * @return
     * @author: hudeyong
     * @date:
     * @modify:
     */
    public Map<String, Object> queryUserByModule(List<CboPermissionModuleEntity> permissionModuleEntities) {
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> addMap = new HashMap<>();
        Map<String, Object> removeMap = new HashMap<>();
        StringBufferProxy sql = new StringBufferProxy();
        for(CboPermissionModuleEntity permissionModuleEntity : permissionModuleEntities){
            String resourceid = ConvertUtil.convertToString(permissionModuleEntity.getResourceid());
            String isUser = ConvertUtil.convertToString(permissionModuleEntity.getIsuser());
            String permissionMode = ConvertUtil.convertToString(permissionModuleEntity.getPermissionmode());
            sql.clear();
            if("0".equals(isUser)){
                // 如果是角色
                sql.appendSingle("id IN (SELECT USERID FROM CBOUSERROLE WHERE ROLEID = '{0}')",resourceid);
            } else if("2".equals(isUser)){
                // 如果是部门
                CboDeptEntity deptEntity = cboDeptService.queryById(resourceid);
                sql.appendSingle("DEPTID IN (SELECT ID FROM CBODEPT WHERE CODE LIKE '{0}%')",deptEntity.getCode());
            } else if("1".equals(isUser)){
                // 如果是人
                sql.appendSingle("id = '{0}'",resourceid);
            } else {
                continue;
            }
            List<CboUserEntity> cboUserEntities = cboUserService.queryByWhere(sql.toString());
            if("1".equals(permissionMode)){
                // 如果是授权白名单
                for(CboUserEntity userEntity : cboUserEntities){
                    addMap.put(userEntity.getCode(),userEntity.getName());
                }
            } else {
                // 如果是授权黑名单
                for(CboUserEntity userEntity : cboUserEntities){
                    removeMap.put(userEntity.getCode(),userEntity.getName());
                }
            }
        }
        // 取在addmap中但不在removemap中的人
        for (Map.Entry<String, Object> entry : addMap.entrySet()) {
            String key = entry.getKey();
            String value = ConvertUtil.convertToString(entry.getValue());
            // 检查键是否在 removeMap中
            if (!removeMap.containsKey(key)) {
                resultMap.put(key, value);
            }
        }
        return resultMap;
    }

    /***
     * @description: 更新用户金刚区、最近使用、一级目录排序
     * @param paraMap
     * @return
     * @author: hudeyong
     * @date:
     * @modify:
     */
    @Override
    public void updateUserAppInfo(Map<String, Object> paraMap) {
        String userCode = ConvertUtil.convertToString(paraMap.get("userCode"));
        String updateValue = ConvertUtil.convertToString(paraMap.get("updateValue"));
        //code/name/sortcode
        cn.hutool.json.JSONArray array = JSONUtil.parseArray(updateValue);
        List<Map<String, Object>> updateValueList = new ArrayList<>();
        array.stream().forEach(temp -> {
            Map<String, Object> tempMap = (Map<String, Object>) temp;
            updateValueList.add(tempMap);
        });
        for(Map<String, Object> map : updateValueList){
            if(!map.containsKey("code")||!map.containsKey("name")||!map.containsKey("sortcode")){
                throw new ServiceException("传参错误！");
            }
        }
        String updateType = ConvertUtil.convertToString(paraMap.get("updateType"));
        StringBufferProxy sql = new StringBufferProxy();
        String fieldName = "";
        if(SystemConst.AppAreaType.corearea.equals(updateType)){
            // 更新金刚区
            fieldName = AppUserUseInfoEntity.FieldCorearea;
        } else if (SystemConst.AppAreaType.recentlyusedarea.equals(updateType)) {
            // 更新最近使用
            fieldName = AppUserUseInfoEntity.FieldRecentlyusedarea;
        } else if (SystemConst.AppAreaType.firstleveldirectory.equals(updateType)) {
            // 更新一级目录排序
            fieldName = AppUserUseInfoEntity.FieldFirstleveldirectory;
        } else if (SystemConst.AppAreaType.extendfield1.equals(updateType)) {
            // 更新文档中心排序
            fieldName = AppUserUseInfoEntity.FieldExtendfield1;
        }
        if(!fieldName.isEmpty()){
            sql.appendSingle("UPDATE {0} SET {1} = '{2}' WHERE USERCODE = '{3}'",
                    AppUserUseInfoEntity.tableName,fieldName ,
                    updateValue, userCode);
            this.updateExecute(sql.toString());
        }
    }

    /**
     * @param listModule
     * @return
     * @Title:
     * @author: hudeyong
     * @return_type: List<Map < String, Object>>
     * @Description: 用户权限接口
     */
    @Override
    public Map<String, Object> getUserPermissions(Map<String, Object> paraMap) throws UnsupportedEncodingException {
        // 获取当前登录用户信息
        SessionUserBean userBean = ThreadLocalContext.sessionUserBeanThreadLocal.get();
        StringBufferProxy sql = new StringBufferProxy();
        // 用户所处角色列表
        sql.appendSingle("id in (select roleid from cbouserrole where  userid = '{0}') and EXTENDFIELD10 is not null",
                userBean.getUser().getId());
        List<CboRoleEntity> roles = cboRoleService.queryByWhere(sql.toString());
        // 所在的所有部门列表
        CboDeptEntity dept = cboDeptService.queryById("" + userBean.getUser().getDeptid());
        // 查询部门以及上级部门
        String deptUser = "";
        List<Map<String, Object>> list = getAllDeptList();
        for (Map<String, Object> deptMap : list) {
            if (ConvertUtil.convertToString(deptMap.get("code")).length() > 0
                    && ConvertUtil.convertToString(dept.getCode())
                    .startsWith(ConvertUtil.convertToString(deptMap.get("code")))
                    && dept.getOrgid() == ConvertUtil.convertToLong(deptMap.get("orgid"))) {
                deptUser += "," + ConvertUtil.convertToLong(deptMap.get("id"));
            }
        }
        if (deptUser.startsWith(",")) {
            deptUser = deptUser.substring(1);
        }
        // 权限菜单
        List<CboModuleEntity> listModule;
        String rootCode = ConvertUtil.convertToString("80");
        List<CboPermissionModuleEntity> permissions = cboPermissionModuleService.queryUserModules(userBean.getUser().getId(),
                roles, deptUser);
        List<String> listModuleId = new ArrayList<>();
        for (int i = 0; permissions != null && i < permissions.size(); i++) {
            CboPermissionModuleEntity per = permissions.get(i);
            if (!listModuleId.contains(ConvertUtil.convertToString(per.getModuleid()))) {
                listModuleId.add(String.valueOf(per.getModuleid()));
            }
        }
        // 查询公开模块
        sql.clear();
        // 黑名单
        permissions = queryRemoveModules(userBean.getUser().getId(),roles, deptUser);
        for (int i = 0; permissions != null && i < permissions.size(); i++) {
            CboPermissionModuleEntity per = permissions.get(i);
            if (listModuleId.contains(ConvertUtil.convertToString(per.getModuleid()))) {
                listModuleId.remove(listModuleId.indexOf(String.valueOf(per.getModuleid())));
            }
        }
        // 最终显示菜单
        listModule = cboModuleService.queryModule(listModuleId, rootCode);
//        List<AppModuleIconEntity> moduleIconEntities =  appModuleIconService.queryAllModuleIcon(paraMap);
//        for(CboModuleEntity moduleEntity : listModule){
//            List<AppModuleIconEntity> moduleIcons = moduleIconEntities.stream().filter( e -> e.getModulecode().equals(moduleEntity.getCode())).collect(Collectors.toList());
//            if(moduleIcons.size()>0){
//                moduleEntity.setImageurl(new String(moduleIcons.get(0).getModuleicon(), "UTF-8"));
//            }
//        }
        String imgUrl = ParameterCache.getValue("imgUrl");
        DatacodeCache datacodeCache = new DatacodeCache();
        for(CboModuleEntity moduleEntity : listModule){
            if(!ConvertUtil.convertToString(moduleEntity.getImageurl()).isEmpty()){
                String fieldName = datacodeCache.getValueDynamic("AppIconCatalog", moduleEntity.getCode().substring(0,4), "code", "name");
                moduleEntity.setImageurl(imgUrl + fieldName + "/" +moduleEntity.getImageurl());
            }
        }
        // 去重
        listModule = listModule.stream().collect(Collectors
                .collectingAndThen(
                        Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(CboModuleEntity::getId))),
                        ArrayList::new));
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("roleList",roles);
        AppTreeModel appTreeModel = new AppTreeModel();
        // 转为树形结构，去除不连续模块
        List<AppTreeModel> treeList = appTreeModel.buildTree(filterModuleList(listModule), false, "");
        for(AppTreeModel parentTreeModel : treeList){
            if(ConvertUtil.convertToLong(parentTreeModel.getPid())==0){
                treeList = parentTreeModel.getValue();
                break;
            }
        }
        // 用户使用信息
        AppUserUseInfoEntity userUseInfoEntity = queryAppVersionInfo(userBean,paraMap);
        // 配置信息
        sql.clear();
        sql.appendSingle("tablename = '{0}' and publish = '1' and enabled = '1'",userUseInfoEntity.getTableName());
        List<AppAreaInitializationConfigEntity> areaInitializationConfigEntities = appAreaInitializationConfigService.queryByWhere(sql.toString());
        List<AppAreaInitializationConfigEntity> tempCoreConfigEntities =
                areaInitializationConfigEntities.stream().filter(item->item.getFieldname().equals(userUseInfoEntity.FieldCorearea)).collect(Collectors.toList());
        // 金刚区最大允许数
        int maxCoreNum = 0;
        if(tempCoreConfigEntities.size()>0){
            maxCoreNum = ConvertUtil.convertToInt(tempCoreConfigEntities.get(0).getMaxnum());

        }
        resultMap.put("maxCoreNum",maxCoreNum);
        List<AppAreaInitializationConfigEntity> tempRecentlyConfigEntities =
                areaInitializationConfigEntities.stream().filter(item->item.getFieldname().equals(userUseInfoEntity.FieldRecentlyusedarea)).collect(Collectors.toList());
        // 最近使用最大允许数
        int maxRecentlyNum = 0;
        if(tempRecentlyConfigEntities.size()>0){
            maxRecentlyNum = ConvertUtil.convertToInt(tempRecentlyConfigEntities.get(0).getMaxnum());
        }
        resultMap.put("maxRecentlyNum",maxRecentlyNum);
        // 用户金刚区
        String coreArea = ConvertUtil.convertToString(userUseInfoEntity.getCorearea());
        // 如果用户金刚区已经为空了
        if(coreArea.isEmpty()){
            List<AppAreaInitializationConfigEntity> tempConfigEntities =
                    areaInitializationConfigEntities.stream().filter(item->item.getFieldname().equals(userUseInfoEntity.FieldCorearea)).collect(Collectors.toList());
            if(tempConfigEntities !=null && tempConfigEntities.size()>0){
                coreArea = tempConfigEntities.get(0).getDefaultvalue();
            }
        }
        // 处理用户金刚区
        List<Map<String, Object>> coreList = new ArrayList<>();
        List<Map<String, Object>> userAreasList = (List<Map<String, Object>>) JSONArray.parse(coreArea);
        // 获取审批中心编码
        String approvalCenterCode = ParameterCache.getValue("ApprovalCenterCode","8000");
        userAreasList = userAreasList.stream().filter(item -> !item.get("code").equals(approvalCenterCode)).collect(Collectors.toList());
        List<AppTreeModel> approvalCenterModuls = treeList.stream().filter(item -> item.getCode().equals(approvalCenterCode)).collect(Collectors.toList());
        if(approvalCenterModuls.size()>0){
            Map<String, Object> ApprovalCenter = new HashMap<>();
            ApprovalCenter.put("code",ConvertUtil.convertToString(approvalCenterModuls.get(0).getCode()));
            ApprovalCenter.put("name",ConvertUtil.convertToString(approvalCenterModuls.get(0).getName()));
            ApprovalCenter.put("sortcode","1");
            userAreasList.add(0,ApprovalCenter);
        }
        int index = 1;
        for(Map<String, Object> map : userAreasList){
            map.put("sortcode",index);
            index++;
            if(index>maxCoreNum){
                break;
            }
        }
        coreList = queryPermissionModule(treeList, coreList, userAreasList);
        List<Map<String, Object>> newCoreAreaList = new ArrayList<>();
        for(Map<String, Object> map : coreList){
            Map<String, Object> tempMap = new HashMap<>();
            tempMap.put("code",ConvertUtil.convertToString(map.get("code")));
            tempMap.put("name",ConvertUtil.convertToString(map.get("name")));
            tempMap.put("sortcode",ConvertUtil.convertToString(map.get("sortcode")));
            newCoreAreaList.add(tempMap);
        }
        coreList = coreList.stream().sorted(Comparator.comparing(e -> ConvertUtil.convertToInt(e.get("sortcode")))).collect(Collectors.toList());
        newCoreAreaList = newCoreAreaList.stream().sorted(Comparator.comparing(e -> ConvertUtil.convertToInt(e.get("sortcode")))).collect(Collectors.toList());
        userUseInfoEntity.setCorearea(JSON.toJSONString(newCoreAreaList));
        resultMap.put("coreList",coreList);
        // 最近使用
        String recentlyusedarea = ConvertUtil.convertToString(userUseInfoEntity.getRecentlyusedarea());
        if(recentlyusedarea.isEmpty()){
            resultMap.put("recentlyList",new ArrayList<>());
        } else {
            List<Map<String, Object>> recentlyList = new ArrayList<>();
            userAreasList = (List<Map<String, Object>>) JSONArray.parse(recentlyusedarea);
            index = 1;
            for(Map<String, Object> map : userAreasList){
                map.put("sortcode",index);
                index++;
                if(index>maxRecentlyNum){
                    break;
                }
            }
            recentlyList = queryPermissionModule(treeList, recentlyList, userAreasList);
            recentlyList = recentlyList.stream().sorted(Comparator.comparing(e -> ConvertUtil.convertToInt(e.get("sortcode")))).collect(Collectors.toList());
            resultMap.put("recentlyList",recentlyList);
        }
        // 一级目录排序
        String firstLevelDirectory = ConvertUtil.convertToString(userUseInfoEntity.getFirstleveldirectory());
        if(firstLevelDirectory.isEmpty()){
            List<AppAreaInitializationConfigEntity> tempConfigEntities =
                    areaInitializationConfigEntities.stream().filter(item->item.getFieldname().equals(userUseInfoEntity.FieldFirstleveldirectory)).collect(Collectors.toList());
            if(tempConfigEntities !=null && tempConfigEntities.size()>0){
                firstLevelDirectory = ConvertUtil.convertToString(tempConfigEntities.get(0).getDefaultvalue());
                userUseInfoEntity.setFirstleveldirectory(firstLevelDirectory);
            }
        }
        treeList = sortPermissionModule(treeList);
        // 取出文档中心数据集,放入结果集
        if(treeList.size() > 0) {
            List<AppTreeModel> documentList = treeList.stream().filter(m -> SystemConst.DOCUMENT_CODE.equals(m.getCode())).collect(Collectors.toList());
            List<AppTreeModel> resList = documentList.get(0).getValue();
            List<AppTreeModel> resListForSort = new ArrayList<AppTreeModel>();
            if (!ConvertUtil.convertToString(userUseInfoEntity.getExtendfield1()).isEmpty()) {
                // 当用户使用信息文档中心有值时
                JSONArray documentCenterJsonArray = JSONArray.parseArray(userUseInfoEntity.getExtendfield1());
                for (int i = 0; i < documentCenterJsonArray.size(); i++ ) {
                    JSONObject jsonObject = documentCenterJsonArray.getJSONObject(i);
                    for(AppTreeModel item : resList) {
                      if (item.getCode().equals(ConvertUtil.convertToString(jsonObject.get("code")))) {
                          resListForSort.add(item);
                          break;
                      }
                    }
                }
            } else {
                // 当用户使用信息文档中心无值，使用文档中心初始化配置默认值
                List<AppAreaInitializationConfigEntity> tempExtendfield1ConfigEntities =
                        areaInitializationConfigEntities.stream().filter(item->item.getFieldname().equals(userUseInfoEntity.FieldExtendfield1)).collect(Collectors.toList());
                if (tempExtendfield1ConfigEntities.size() == 0) {
                    resListForSort = resList;
                } else {
                    JSONArray documentCenterJsonArray = JSONArray.parseArray(tempExtendfield1ConfigEntities.get(0).getDefaultvalue());
                    for (int i = 0; i < documentCenterJsonArray.size(); i++) {
                        JSONObject jsonObject = documentCenterJsonArray.getJSONObject(i);
                        for (AppTreeModel item : resList) {
                            if (item.getCode().equals(ConvertUtil.convertToString(jsonObject.get("code")))) {
                                resListForSort.add(item);
                                break;
                            }
                        }
                    }
                }
            }
            // 排序前后不一致的情况、筛选出缺失的模块内容，补充在尾部
            if (resListForSort.size() != resList.size()) {
                Set<AppTreeModel> resSet = new HashSet<>(resList);
                List<AppTreeModel> filteredList = new ArrayList<>();
                for (AppTreeModel item : resListForSort) {
                    if (!resSet.contains(item)) {
                        filteredList.add(item);
                    }
                }
                resListForSort.addAll(filteredList);
            }
            resultMap.put("documentList", resListForSort);
        }else{
            List<AppTreeModel> resList = new ArrayList<>();
            resultMap.put("documentList", resList);
        }
        removeEmptyDirectories(treeList);
        resultMap.put("modeuleList",directoryFirstLevel(treeList, firstLevelDirectory));
        if(userUseInfoEntity.getId()>0) {
            this.updateEntity(userUseInfoEntity);
        } else {
            this.insert(userUseInfoEntity);
        }
        return resultMap;
    }

    /**
     * @param listModule
     * @return
     * @Title:
     * @author: hudeyong
     * @return_type: List<Map < String, Object>>
     * @Description: 排序一级目录
     */
    private List<AppTreeModel> directoryFirstLevel(List<AppTreeModel> treeList, String firstLevelDirectory) {
        List<Map<String,Object>> firstLevelDirectoryList = ((List<Map<String, Object>>) JSONArray.parse(firstLevelDirectory));
        // 一级菜单是目录的
        treeList = treeList.stream().filter(item-> SystemConst.AppModuleType.catalog.equals(ConvertUtil.convertToString(item.getType()))).collect(Collectors.toList());
        // 根据个人一级目录排序进行排序
        int index = 1;
        for(Map<String,Object> map : firstLevelDirectoryList){
            for(AppTreeModel appTreeModel : treeList){
                if(appTreeModel.getCode().equals(ConvertUtil.convertToString(map.get("code")))){
                    appTreeModel.setSortcode(index+"");
                    index++;
                    break;
                }
            }
        }
        return treeList.stream().sorted(Comparator.comparingInt(e -> ConvertUtil.convertToInt(e.getSortcode()))).collect(Collectors.toList());
    }

    private List<AppTreeModel> sortPermissionModule(List<AppTreeModel> treeList) {
        for(AppTreeModel appTreeModels : treeList){
            if(appTreeModels.getValue()!=null){
                appTreeModels.setValue(appTreeModels.getValue().stream().sorted(Comparator.comparing(e -> ConvertUtil.convertToInt(e.getSortcode()))).collect(Collectors.toList()));
                sortPermissionModule(appTreeModels.getValue());
            }
        }
        return treeList;
    }

    /**
     * @param List<AppTreeModel>
     * @return
     * @Title: removeEmptyDirectories
     * @author: hudeyong
     * @return_type: void
     * @Description: 去除没有模块的目录
     */
    public void removeEmptyDirectories(List<AppTreeModel> treeList) {
        // 遍历树形结构中的每个节点
        Iterator<AppTreeModel> iterator = treeList.iterator();
        while (iterator.hasNext()) {
            AppTreeModel node = iterator.next();
            // 如果该节点为目录且没有孩子，则将其从父节点中移除
            if (SystemConst.AppModuleType.catalog.equals(node.getType()) && node.getValue() == null) {
                iterator.remove();
            } else if (node.getValue() != null) {
                // 如果该节点有孩子，则递归地处理其孩子
                removeEmptyDirectories(node.getValue());
            }
        }
    }

    /**
     * @param listModule
     * @return
     * @Title: queryUserCoreArea
     * @author: hudeyong
     * @return_type: List<Map < String, Object>>
     * @Description: 查询是否有模块权限，返回有权限的模块
     */
    private List<Map<String, Object>> queryPermissionModule(List<AppTreeModel> treeList, List<Map<String, Object>> permissionModules, List<Map<String, Object>> userAreasList) {
        for(AppTreeModel appTreeModels : treeList){
            List<Map<String, Object>> tempList = userAreasList.stream().filter(item->appTreeModels.getCode().equals(ConvertUtil.convertToString(item.get("code")))).collect(Collectors.toList());
            if(tempList.size()>0){
                Map<String, Object> tempMap = new HashMap<>();
                tempMap.put("mobileCode", appTreeModels.getMobileCode());
                tempMap.put("mobileName", appTreeModels.getMobileName());
                tempMap.put("code", appTreeModels.getCode());
                tempMap.put("name", appTreeModels.getName());
                tempMap.put("id", appTreeModels.getId());
                tempMap.put("pid", appTreeModels.getPid());
                tempMap.put("icon", appTreeModels.getIcon());
                tempMap.put("routerpath", appTreeModels.getRouterpath());
                tempMap.put("sortcode", ConvertUtil.convertToString(tempList.get(0).get("sortcode")));
                // 新增
                tempMap.put("type",appTreeModels.getType());
                tempMap.put("value",appTreeModels.getValue());
                permissionModules.add(tempMap);
            }
            if(appTreeModels.getValue()!=null){
                queryPermissionModule(appTreeModels.getValue() ,permissionModules, userAreasList);
            }
        }
        return permissionModules;
    }

    /**
     * @param listModule
     * @return
     * @Title: filterModuleList
     * @author: hudeyong
     * @return_type: List<Map < String, Object>>
     * @Description: 过滤手机端权限模块
     */
    private List<Map<String, Object>> filterModuleList(List<CboModuleEntity> listModule) {
        List<Map<String, Object>> result = new ArrayList<>();
        for (CboModuleEntity cboModuleEntity : listModule) {
            // 扩展字段1为手机端编码，扩展字段2为手机端模块名称
            Map<String, Object> module = new HashMap<>();
            if (cboModuleEntity.getExtendfield2() != null && !"".equals(cboModuleEntity.getExtendfield2())) {
                module.put("mobileName", cboModuleEntity.getName());
                module.put("name", cboModuleEntity.getName());
            } else {
                module.put("mobileName", cboModuleEntity.getName());
                module.put("name", cboModuleEntity.getName());
            }
            module.put("mobileCode", cboModuleEntity.getExtendfield1());
            module.put("id", cboModuleEntity.getId());
            module.put("code", cboModuleEntity.getCode());
            module.put("parentid", cboModuleEntity.getParentid());
            module.put("type", cboModuleEntity.getExtendfield2());
            module.put("routerpath", cboModuleEntity.getExtendfield3());
            module.put("icon", cboModuleEntity.getImageurl());
            module.put("sortcode", cboModuleEntity.getSortcode());
            result.add(module);
        }
        return result;
    }

    /**
     * @Description:    获取部门信息
     * @Author:         hudeyong
     * @Date:           2022/12/28
     * @Version:        1.0
     */
    private List<Map<String, Object>> getAllDeptList() {
        String sql = "enabled=1";
        String key = "alldeptlist" + sql;
        List<Map<String, Object>> list = null;
        Object object = getObject(key);
        if (null == object) {
            List<String> filedList = new ArrayList<String>();
            filedList.add("code");
            filedList.add("orgid");
            filedList.add("id");
            list = cboDeptService.queryMapFieldsByWhere("enabled=1", filedList);
            putObject(key, list);
        }
        else {
            list = (List<Map<String, Object>>) object;
        }
        return list;
    }

    /*
     * 手机版本信息录入
     *
     * */
    public AppUserUseInfoEntity queryAppVersionInfo(SessionUserBean userBean, Map<String, Object> paraMap) {
        String usercode = ConvertUtil.convertToString(userBean.getUser().getCode());
        String username = ConvertUtil.convertToString(userBean.getUser().getName());
        String tel = ConvertUtil.convertToString(userBean.getUser().getMobile());
        String companyname = ConvertUtil.convertToString(userBean.getOrg().getShortname());
        String deptname = ConvertUtil.convertToString(userBean.getDept().getFullname());
        if(usercode.isEmpty()) {
            return new AppUserUseInfoEntity();
        }
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle("usercode = '{0}'", usercode);
        List<AppUserUseInfoEntity> appUserUseInfoEntities = this.queryByWhere(sql.toString());
        AppUserUseInfoEntity appUserUseInfoEntity = new AppUserUseInfoEntity();
        if(appUserUseInfoEntities.size()>0) {
            appUserUseInfoEntity = appUserUseInfoEntities.get(0);
        }
        appUserUseInfoEntity.setUsertel(tel);
        appUserUseInfoEntity.setUsercode(usercode);
        appUserUseInfoEntity.setUsername(username);
        appUserUseInfoEntity.setCompanyname(companyname);
        appUserUseInfoEntity.setDeptname(deptname);
        String deviceType = ConvertUtil.convertToString(paraMap.get("deviceType"));
        appUserUseInfoEntity.setDeviceType(deviceType);
        if(paraMap.containsKey("versionCode") && paraMap.containsKey("versionName")) {
            String versionCode = ConvertUtil.convertToString(paraMap.get("versionCode"));
            String versionName = ConvertUtil.convertToString(paraMap.get("versionName"));
            appUserUseInfoEntity.setVersioncode(versionCode);
            appUserUseInfoEntity.setVersionname(versionName);
            if(appUserUseInfoEntities.size()>0) {
                this.updateEntity(appUserUseInfoEntity);
            } else {
                this.insert(appUserUseInfoEntity);
            }
        } else {
            appUserUseInfoEntity.setVersioncode("0");
            appUserUseInfoEntity.setVersionname("0");
//            if(appUserUseInfoEntities.size()>0) {
//                this.updateEntity(appUserUseInfoEntity);
//            } else {
//                this.insert(appUserUseInfoEntity);
//            }
        }
        return appUserUseInfoEntity;
    }

    public List<CboPermissionModuleEntity> queryRemoveModules(long userId, List<CboRoleEntity> roles, String deptIds) {
        String roleIds = "";
        for (int i = 0; i < roles.size(); i++) {
            CboRoleEntity role = roles.get(i);
            String roleId = "'" + role.getId() + "'";
            if (i == roles.size() - 1)
                roleIds = roleIds + roleId;
            else
                roleIds = roleIds + roleId + ",";
        }
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle("(IsUser=1 AND ResourceId={0} AND PERMISSIONMODE = '0')", userId);
        if(roleIds != null &&  !"".equals(roleIds)) {
            sql.appendSingle(" OR (IsUser=0 AND ResourceId IN ({0}) AND PERMISSIONMODE = '0')", roleIds);
        }
        if(deptIds != null && !"".equals(deptIds)) {
            sql.appendSingle(" OR (IsUser=2 AND ResourceId IN ({0}) AND PERMISSIONMODE = '0')", deptIds);
        }
        List<CboPermissionModuleEntity> cboPermissionModuleEntities = cboPermissionModuleService.queryByWhere(sql.toString());
        return cboPermissionModuleEntities;
    }

    public void putObject(Object key, Object value) {
        if (key == null) {
            return;
        }
        String keystring = getKey(key);
        redisTemplate.opsForValue().set(keystring, value, cacheLiveTime, TimeUnit.SECONDS);
    }

    public Object getObject(Object key) {
        if (key == null) {
            return null;
        }
        String keystring = getKey(key);
        return redisTemplate.opsForValue().get(keystring);
    }

    private String getKey(Object key) {
        return "mybatis:" + "cbodeptentity" + ":" + key.toString();
    }

    public void SyncRoleAndUserRole(String syncSys, SqlSessionTemplate syncTemplate) {
        StringBufferProxy sql = new StringBufferProxy();
        String syncSysModule= "syncSysModule";
        if ("crm".equals(syncSys)) {
            syncSysModule= "syncCrmModule";
        }
        Map<String,Object> paramMap = new HashMap<>();
        // 获取系统同步时间
        sql.appendSingle(" itemid = (select id from cboitems where code = 'AppSysModuleList') and code = '{0}' ",syncSys);
        List<CboItemDetailsEntity> cboItemDetailsEntities = cboItemDetailsService.queryByWhere(sql.toString());
        sql.clear();
        if(cboItemDetailsEntities.size()==0) {
            return ;
        }
        // 系统简称
        String syscode = ConvertUtil.convertToString(cboItemDetailsEntities.get(0).getCode());
        // 同步时间
        String time = ConvertUtil.convertToString(cboItemDetailsEntities.get(0).getName());
        // 获取时间段内的角色变化
        paramMap.put("time", time);
        List<Map<String, Object>> oldrolelist = syncTemplate.selectList(syncSysModule+".queryRecentRole", paramMap);
        // 如果这段时间内角色有变化，进行新增或更新
        if(oldrolelist.size()>0) {
            for(Map<String, Object> map : oldrolelist) {
                String oldid = ConvertUtil.convertToString(map.get("id"));
                // 查找是否有这个角色
                sql.clear();
                sql.appendSingle("EXTENDFIELD9 = '{0}' and EXTENDFIELD10 = '{1}'",ConvertUtil.convertToString(map.get("id")),syscode);
                List<CboRoleEntity> cboRoleEntities = cboRoleService.queryByWhere(sql.toString());
                System.out.println("---------------------------------"+ ConvertUtil.convertToString(map.get("code")) +"---------------------------------");
                if(!ConvertUtil.convertToString(map.get("code")).isEmpty()){
                    map.put("code",syscode+"-"+ConvertUtil.convertToString(map.get("code")));
                }
                if(cboRoleEntities.size()>0) {
                    // 如果有就更新
                    changeRole(map,syscode,"update",syncSys,cboRoleEntities.get(0).getId());

                } else {
                    // 如果没有就新增
                    changeRole(map,syscode,"insert",syncSys,0);
                }
            }
        }
        // 查找系统的角色数量，与本系统对比是否一致
        oldrolelist = syncTemplate.selectList(syncSysModule+".queryAllRole", paramMap);
        sql.clear();
        sql.appendSingle("EXTENDFIELD10 = '{0}'",syncSys);
        List<CboRoleEntity> rolelist = cboRoleService.queryByWhere(sql.toString());
        // 角色个数不相同--权限中心大于旧系统角色人员人数  说明旧系统角色人员人数有删除的，需要遍历删除
        if(rolelist.size() > oldrolelist.size()) {
            List<String> list = new ArrayList<String>();
            for(Map<String, Object> map : oldrolelist) {
                String id = ConvertUtil.convertToString(map.get("id"));
                list.add(id);
            }
            StringBuffer delids = new StringBuffer();
            for(CboRoleEntity roleEntity : rolelist) {
                String oldSysId = ConvertUtil.convertToString(roleEntity.getExtendfield9());
                if(!list.contains(oldSysId)) {
                    delids.append("'").append(oldSysId).append("',");
                }
            }
            if(delids.toString().length()>0) {
                sql.clear();
                sql.appendSingle("EXTENDFIELD9 in ({0}) and EXTENDFIELD10 = '{1}'",delids.toString().substring(0,delids.toString().length()-1),syscode);
                cboRoleService.deleteByWhere(sql.toString());
            }
        }
        // 角色人员处理
        // 查找角色人员表中在time时间内修改的所有数据。
        List<Map<String, Object>> olduserrolelist = syncTemplate.selectList(syncSysModule+".queryRecentUserRole", paramMap);
        if(oldrolelist.size()>0) {
            for(Map<String, Object> map : olduserrolelist) {
                String oldsysid = ConvertUtil.convertToString(map.get("id"));
                String oldsysroleid = ConvertUtil.convertToString(map.get("roleid"));
                sql.clear();
                // 本系统该角色人员对应的角色
                sql.appendSingle("EXTENDFIELD9 = '{0}'",oldsysroleid,syscode);
                List<CboRoleEntity> cboRoleEntities = cboRoleService.queryByWhere(sql.toString());
                cboRoleEntities = cboRoleEntities.stream().filter(item->item.getExtendfield10().equals(syncSys)).collect(Collectors.toList());
                sql.clear();
                sql.appendSingle("DESCRIPTION = '{0}'",syscode+oldsysid);
                // 如果本系统没有对应角色
                if(cboRoleEntities.size()==0){
                    // 如果本系统没有对应角色，删除这个角色人员
                    cboUserRoleService.deleteByWhere(sql.toString());
                    continue;
                }
                // 本系统该角色人员对应的角色的id
                long newsysroleid = cboRoleEntities.get(0).getId();
                // 查找本系统是否有这个角色人员----
                List<CboUserRoleEntity> userRoleEntities = cboUserRoleService.queryByWhere(sql.toString());
                if(userRoleEntities.size()>0) {
                    // 如果有就更新
                    changeUserRole(map,syscode,"update",syncTemplate,syncSysModule,userRoleEntities.get(0).getDescription(),newsysroleid);
                } else {
                    // 如果没有就新增
                    changeUserRole(map,syscode,"insert",syncTemplate,syncSysModule,"",newsysroleid);
                }
            }
        }
        // 查找系统的角色人员数量，与本系统对比是否一致
        olduserrolelist = syncTemplate.selectList(syncSysModule+".queryAllUserRole", paramMap);
        sql.clear();
        sql.appendSingle("ROLEID IN (SELECT id FROM CBOROLE WHERE EXTENDFIELD10 = '{0}')",syncSys);
        List<CboUserRoleEntity> userrolelist = cboUserRoleService.queryByWhere(sql.toString());
        // 角色个数不相同--权限中心大于旧系统角色人员人数  说明旧系统角色人员人数有删除的，需要遍历删除
        if(userrolelist.size() > olduserrolelist.size()) {
            List<String> list = new ArrayList<>();
            for(Map<String, Object> map : olduserrolelist) {
                String oldFlag = ConvertUtil.convertToString(syscode+map.get("id"));
                list.add(oldFlag);
            }
            StringBuffer delFlags = new StringBuffer();
            int index = 0;
            for(CboUserRoleEntity userRoleEntity : userrolelist) {
                String flag = ConvertUtil.convertToString(userRoleEntity.getDescription());
                if(!list.contains(flag)) {
                    delFlags.append("'").append(flag).append("',");
                    // 每500删一次
                    index++;
                    if(index==500){
                        index=0;
                        sql.clear();
                        sql.appendSingle("DESCRIPTION in ({0})",delFlags.toString().substring(0,delFlags.toString().length()-1));
                        cboUserRoleService.deleteByWhere(sql.toString());
                        delFlags = new StringBuffer();
                    }
                }
            }
            if(delFlags.toString().length()>0) {
                sql.clear();
                sql.appendSingle("DESCRIPTION in ({0})",delFlags.toString().substring(0,delFlags.toString().length()-1));
                cboUserRoleService.deleteByWhere(sql.toString());
            }
        }
        return;
    }

    private void changeRole(Map<String, Object> map,String sys,String changetype,String syncSys,long newSysRoleId) {
        CboRoleEntity cboRoleEntity = new CboRoleEntity();
//        String newroleid = number+map.get("id");
//        cboRoleEntity.setId(ConvertUtil.convertToLong(newroleid));
        cboRoleEntity.setCode(ConvertUtil.convertToString(map.get("code")));
        cboRoleEntity.setName(ConvertUtil.convertToString((syncSys)+map.get("name")));
        cboRoleEntity.setOrgid(ConvertUtil.convertToLong(map.get("orgid")));
        cboRoleEntity.setCategory(ConvertUtil.convertToString(map.get("category")));
        cboRoleEntity.setIsvisible(ConvertUtil.convertToInt(map.get("isvisible")));
        cboRoleEntity.setExtendfield1(ConvertUtil.convertToString(map.get("extendfield1")));
        cboRoleEntity.setExtendfield2(ConvertUtil.convertToString(map.get("extendfield2")));
        cboRoleEntity.setExtendfield3(ConvertUtil.convertToString(map.get("extendfield3")));
        cboRoleEntity.setExtendfield4(ConvertUtil.convertToString(map.get("extendfield4")));
        cboRoleEntity.setExtendfield5(ConvertUtil.convertToString(map.get("extendfield5")));
        cboRoleEntity.setExtendfield6(ConvertUtil.convertToString(map.get("extendfield6")));
        cboRoleEntity.setExtendfield7(ConvertUtil.convertToString(map.get("extendfield7")));
        cboRoleEntity.setExtendfield8(ConvertUtil.convertToString(map.get("extendfield8")));
        cboRoleEntity.setExtendfield9(ConvertUtil.convertToString(map.get("id")));
        cboRoleEntity.setExtendfield10(sys);
        cboRoleEntity.setSortCode(ConvertUtil.convertToInt(map.get("sortcode")));
        cboRoleEntity.setDescription(ConvertUtil.convertToString(map.get("description")));
        cboRoleEntity.setEnabled(ConvertUtil.convertToInt(map.get("enabled")));
        if(changetype.equals("insert")) {
            long roleid = PrimaryKeyUtil.GeneIDs(cboRoleEntity.getTableName(), 1)[0];
            cboRoleEntity.setId(roleid);
            cboRoleService.insert(cboRoleEntity);
        } else {
            cboRoleEntity.setId(newSysRoleId);
            cboRoleService.updateEntity(cboRoleEntity);
        }
    }

    private void changeUserRole(Map<String, Object> map,String sys,String changetype,
                                SqlSessionTemplate syncTemplate, String syncSysModule,String newsysid, long newsysroleid) {
        CboUserRoleEntity cbouserRoleEntity = new CboUserRoleEntity();
        // 原系统id
        String oldSysId = ConvertUtil.convertToString(map.get("id"));
        Map<String,Object> paramMap = new HashMap<>();
        // 原系统人员
        paramMap.put("userid", map.get("userid"));
        // 查找原系统有没有这个人
        List<Map<String, Object>> user = syncTemplate.selectList(syncSysModule+".queryUser", paramMap);
        if(user==null || user.size()==0) {
            return;
        }
//        cbouserRoleEntity.setId(ConvertUtil.convertToLong(newid));
        // 查找本系统这个人的信息
        StringBufferProxy sql = new StringBufferProxy();
        sql.clear();
        sql.appendSingle("code = '{0}'", user.get(0).get("code"));
        List<CboUserEntity> cboUserEntities = cboUserService.queryByWhere(sql.toString());
        if(cboUserEntities == null || cboUserEntities.size()==0) {
            return;
        }
        // 将原系统的代号_id放到备注里
        cbouserRoleEntity.setDescription(sys+oldSysId);
        // 赋值转换过来的人
        cbouserRoleEntity.setUserid(ConvertUtil.convertToLong(cboUserEntities.get(0).getId()));
        // 赋值本系统对应的人员
        cbouserRoleEntity.setRoleid(ConvertUtil.convertToLong(newsysroleid));
        if(changetype.equals("insert")) {
            long userroleid = PrimaryKeyUtil.GeneIDs(cbouserRoleEntity.getTableName(), 1)[0];
            cbouserRoleEntity.setId(userroleid);
            cboUserRoleService.insert(cbouserRoleEntity);
        } else {
            cbouserRoleEntity.setId(ConvertUtil.convertToLong(newsysid.substring(sys.length())));
            cboUserRoleService.updateEntity(cbouserRoleEntity);
        }
    }

    @Override
    public Map<String, Object> queryUserModule(Map<String, Object> paraMap) {
        SessionUserBean userBean = ThreadLocalContext.sessionUserBeanThreadLocal.get();
        Map<String, Object> resultMap = new HashMap<>();
        List<Map<String, Object>> resultList = new ArrayList<>();
        if(!paraMap.containsKey("qry_nameList")){
            throw new MessageException("传参错误！");
        }
        // 搜索关键字
        List<String> nameList = (List<String>) paraMap.get("qry_nameList");
        if(nameList == null || nameList.size()==0){
            resultMap.put("resultList",resultList);
            return resultMap;
        }
        List<String> newList = nameList.subList(0, Math.min(nameList.size(), 5));
        // 查询用户id、所处角色、部门含上级
        paraMap.put("usercode",userBean.getUser().getCode());
        List<Map<String, Object>> userInfoList = this.queryMap(paraMap, "queryUserInfo");
        if (userInfoList.size() == 0) {
            throw new MessageException("未找到该用户！");
        }
        // 查询被授权的模块
        Map<String, Object> queryMap = userInfoList.get(0);
        queryMap.put("qry_namelist", newList);
        queryMap.put("usercode",userBean.getUser().getCode());
        List<Map<String, Object>> moduleList = this.queryMap(queryMap,"queryUserModule");
        DatacodeCache datacodeCache = new DatacodeCache();
        String imgUrl = ParameterCache.getValue("imgUrl");
        for (Map<String, Object> map : moduleList) {
            // 扩展字段1为手机端编码，扩展字段2为手机端模块名称
            Map<String, Object> module = new HashMap<>();
            module.put("mobileName", ConvertUtil.convertToString(map.get("name")));
            module.put("name", ConvertUtil.convertToString(map.get("name")));
            module.put("mobileCode", ConvertUtil.convertToString(map.get("extendfield1")));
            module.put("id", ConvertUtil.convertToString(map.get("id")));
            module.put("code", ConvertUtil.convertToString(map.get("code")));
            module.put("parentid", ConvertUtil.convertToString(map.get("parentid")));
            module.put("type", ConvertUtil.convertToString(map.get("extendfield2")));
            module.put("routerpath", ConvertUtil.convertToString(map.get("extendfield3")));
            module.put("sortcode", ConvertUtil.convertToString(map.get("sortcode")));
            module.put("fullname", ConvertUtil.convertToString(map.get("fullname")));
            String fieldName = "";
            if(!ConvertUtil.convertToString(map.get("imageurl")).isEmpty()) {
                fieldName = imgUrl
                        + datacodeCache.getValueDynamic("AppIconCatalog", ConvertUtil.convertToString(map.get("code")).substring(0,4), "code", "name")
                        + "/"
                        + ConvertUtil.convertToString(map.get("imageurl"));
            }
            module.put("icon", fieldName);
            resultList.add(module);
        }
        resultMap.put("resultList",resultList);
        resultMap.put("totalCount",resultList.size());
        return resultMap;
    }
}
